package com.ljc.cjgl.service;

import java.util.HashMap;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ljc.cjgl.custom.TableResult;
import com.ljc.cjgl.entitiy.Scoring;
import com.ljc.cjgl.entitiy.ScoringGrade;
import com.ljc.cjgl.entitiy.Stu;
import com.ljc.cjgl.entitiy.Student;
import com.ljc.cjgl.entitiy.Tea;
import com.ljc.cjgl.entitiy.Teacher;
import com.ljc.cjgl.repository.ScoringGradeRepository;

@Service
public class ScoringGradeService {
	@Autowired
	private ScoringGradeRepository scoringGradeDAO;
	
	public ScoringGrade findById(Integer id) {
		Optional<ScoringGrade> optional = scoringGradeDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	
	public List<ScoringGrade> findAll(){
		return scoringGradeDAO.findAll();
	}
	
	public Page<ScoringGrade> findAll(Specification<ScoringGrade> spec,Pageable pageable){
		return scoringGradeDAO.findAll(spec, pageable);
	}

	public List<ScoringGrade> findAll(Specification<ScoringGrade> specification) {
		return scoringGradeDAO.findAll(specification);
	}
	
	@Transactional
	public synchronized void checkRecord(List<ScoringGrade> list, List<Scoring> scorings, Tea teacher, Stu stu) {
		if(list.size()>0&&list.size()<scorings.size()) {
			scoringGradeDAO.deleteAll(list);
		}
		if(list.isEmpty()) {
			for (Scoring scoring : scorings) {
				ScoringGrade sg=new ScoringGrade();
				sg.setScoring(scoring);
				sg.setStudent(stu);
				sg.setTeacher(teacher);
				scoringGradeDAO.save(sg);
			}
		}
		
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public HashMap<String,Object> gradeChange(Integer id, Integer grade) {
		ScoringGrade model = findById(id);
		model.setGrade(grade);
		scoringGradeDAO.save(model);
		return TableResult.bulidResult(true, "评分保存成功");
	}
	
}
